/*
 * Copyright (c) Huawei Device Co., Ltd. 2023. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "application_parser.h"

#include "loghelper.h"
#include "system_ability_definition.h"

namespace OHOS {
namespace SE {
static sptr<AppExecFwk::IBundleMgr> bundleMgrProxy_;

sptr<AppExecFwk::IBundleMgr> ApplicationParser::GetBundleMgrProxy()
{
    sptr<ISystemAbilityManager> systemAbilityManager =
        SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
    if (!systemAbilityManager) {
        ErrorLog("GetBundleMgrProxy, systemAbilityManager is null");
        return nullptr;
    }
    sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
    if (!remoteObject) {
        ErrorLog("GetBundleMgrProxy, remoteObject is null");
        return nullptr;
    }
    return iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
}

/**
 * @brief Get the bundle name(package name) of the calling application.
 * @param uid The uid of calling application.
 * @return The bundle name(package name) of the calling application..
 */
std::string ApplicationParser::GetBundleNameByUid(const uint32_t& uid)
{
    std::string bundleName;
    bundleMgrProxy_ = GetBundleMgrProxy();
    if (bundleMgrProxy_ == nullptr) {
        ErrorLog("GetBundleNameByUid: GetNameForUid failed, bundleMgrProxy_ is nullptr.");
        return std::string();
    }
    int ret = bundleMgrProxy_->GetNameForUid(uid, bundleName);
    if (ret == ERR_OK) {
        return bundleName;
    } else {
        ErrorLog("GetBundleNameByUid: GetNameForUid failed, ret = %{public}d.", ret);
        return std::string();
    }
}

/**
 * @brief The calling application is system application or not.
 * @param uid The uid of calling application.
 * @return True is system application, otherwise false.
 */
bool ApplicationParser::IsSystemApplication(uint32_t uid)
{
    // need to check the application is system or not.
    InfoLog("ApplicationParser::IsSystemApplication uid = %{public}d", uid);
    bundleMgrProxy_ = GetBundleMgrProxy();
    if (bundleMgrProxy_ == nullptr) {
        return false;
    }
    return bundleMgrProxy_->CheckIsSystemAppByUid(uid);
}
}
}
